/*
 * threadTest.c
 *
 *  Created on: Apr 9, 2011
 *      Author: xozyain
 */

#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"

#define STK_SZ 8092

int semid;
int * tmp;

void * work(void){

	while(1){
		binary_sem_down(semid);
		printf(1,"Process %d Thread %d is running\n", thread_getProcId(), thread_getid());
		printf(1,"Process %d Thread %d is running\n", thread_getProcId(), thread_getid());
		printf(1,"Process %d Thread %d is running\n", thread_getProcId(), thread_getid());
		binary_sem_up(semid);
		sleep(1);
	}

	return 0;
}


int
main(int argc, char *argv[])
{
	int semid,i;
	int num;
	int j;
	void * stack;
	int * threadsArr;


	// Create our single binary semaphore
	semid = binary_sem_create();
	tmp = &j;

	if (argc < 2){
		printf(2,"Usage: ./threadTest [number of threads]\n");
		exit();
	}

	num = atoi(argv[1]);
	threadsArr = (int*)malloc(sizeof(int)*num);

	for (i = 0; i < num; ++i) {
		stack = malloc(STK_SZ);
		threadsArr[i] = thread_create(&work, stack, STK_SZ);
	}

	for (i = 0; i < num; ++i) {
		thread_join(threadsArr[i], (void**)&tmp);
	}


	exit();
	return 1;
}
